#include <func.h>
typedef struct {
    pthread_mutex_t mutex;
    long tickets;
}args_t;

void* thread1(void * p)
{
    int counter = 0;
    args_t* data = (args_t*)p;
    while(1)
    {
        pthread_mutex_lock(&data->mutex);
        if(data->tickets>0)
        {
        //pthread_mutex_lock(&data->mutex);
            printf("1111111: sale tickets\n");
            data->tickets-=1;
            counter++;
            printf("1111111: done,%ld tickets left\n",data->tickets);
            pthread_mutex_unlock(&data->mutex);
        }else{
            pthread_mutex_unlock(&data->mutex);
            printf("thread1: sold %d tickets\n",counter);
            break;
        }
    }
}
void* thread2(void * p)
{
    int counter = 0;
    args_t* data = (args_t*)p;
    while(1)
    {
        pthread_mutex_lock(&data->mutex);
        if(data->tickets>0)
        {
        //pthread_mutex_lock(&data->mutex);
            printf("2222222: sale tickets\n");
            data->tickets-=1;
            counter++;
            printf("2222222: done,%ld tickets left\n",data->tickets);
            pthread_mutex_unlock(&data->mutex);
        }else{
            printf("thread2: sold %d tickets\n",counter);
            pthread_mutex_unlock(&data->mutex);
            break;
        }
    }
}
int main(int argc,char **argv)
{
    ARGS_CHECK(argc,2);
    args_t data;
    pthread_mutex_init(&data.mutex,NULL);
    data.tickets = atoi(argv[1]);
    
    pthread_t pthid1,pthid2;
    
    pthread_create(&pthid1,NULL,thread1,&data);
    pthread_create(&pthid2,NULL,thread2,&data);
    pthread_join(pthid1,NULL);
    pthread_join(pthid2,NULL);
    
    return 0;
}

